<template>
  <div class='add-subjects'>
    <el-dialog :title="dialogTitle" :visible="showDialog" width="20%" @close="handleCloseDialog">
      <el-form :model="form" :rules="rules" ref="addForm">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="form.subjectName" style="width: 200px" placeholder="请输入学科名称"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            >
          </el-switch>
        </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'AddSubjects',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    dialogTitle () {
      return this.form.id ? '修改学科' : '新增学科'
    }
  },
  data () {
    return {
      form: {
        subjectName: '',
        isFrontDisplay: true
      },
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    // 关闭对话框
    handleCloseDialog () {
      this.$emit('update:showDialog', false)
      this.form = {
        subjectName: '',
        isFrontDisplay: true
      }
      this.$refs.addForm.resetFields()
    },
    // 处理新增和修改学科确认
    handleSubmit () {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return
        if (this.form.id) {
          await update(this.form)
          this.$message.success('修改学科成功')
        } else {
          await add(this.form)
          this.$message.success('新增学科成功')
        }
        this.$emit('add-subjects')
        this.handleCloseDialog()
      })
    },
    // 修改学科表单回显
    async getDetail (info) {
      const { data } = await detail(info)
      this.form = data
      // 将数据类型转成布尔类型
      this.form.isFrontDisplay = Boolean(data.isFrontDisplay)
    }
  }
}
</script>

<style scoped lang='scss'>
</style>
